package action

import (
	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/gorm"

	"ssnotify/common/constant"
	"ssnotify/common/enums/able"
	"ssnotify/common/enums/notifysource"
	"ssnotify/common/utils"
	"ssnotify/internal/notify/models"
	"ssnotify/internal/notify/models/query"
)

// 告警消息处理
func handleAlarmNotify(db *gorm.DB, notifyData map[string]interface{}) {
	//数据有效校验
	alarmType := utils.GetStringValueFiled(notifyData, "alarmType")
	alarmLevel := utils.GetIntValueFiled(notifyData, "alarmLevel")
	if len(alarmType) == 0 || alarmLevel == 0 {
		return
	}
	sn := utils.GetStringValueFiled(notifyData, "sn")
	if len(sn) == 0 {
		return
	}
	//设备分组缓存
	deptId, _ := env.Cache.HashGet(constant.DeviceDeptCache, sn)
	if len(deptId) == 0 {
		deptId = constant.DefaultGroupId
	}
	// 有个叫强烈的人要求有分组名
	groupIdName, _ := utils.GroupIdName(db, []string{deptId})
	//缓存最新的分组id
	notifyData["deptId"] = deptId
	notifyData["deptName"] = groupIdName[deptId]
	//查询当前告警数据对应的通知配置信息
	queryConfig := &query.NotifyConfigGetReq{
		Source:   notifysource.Alarm.Get().Source,
		Status:   able.Enable,
		DeptIdEq: deptId,
	}
	//查询数据对应的通知配置
	notifyConfigModel := &models.NotifyConfig{}
	notifyConfigModel.Orm = db
	configList, err := notifyConfigModel.FindNotifyConfig(queryConfig)
	if err != nil {
		logger.Error(err)
		return
	}
	if len(configList) == 0 {
		return
	}
	//遍历所有的配置
	for _, notifyConfig := range configList {
		//获取通知的模板id配置
		templateIds := notifyConfig.TemplateId
		//不存在直接跳过处理
		if len(notifyConfig.Source) == 0 || len(templateIds) == 0 {
			continue
		}
		if len(notifyConfig.Type) > 0 {
			// 告警通知触发, 匹配告警类型、告警级别
			typemap := utils.BytesToMap([]byte(notifyConfig.Type))
			configAlarmType := utils.GetStringValueFiled(typemap, "alarmType")
			if len(configAlarmType) > 0 && configAlarmType != alarmType {
				continue
			}
			configAlarmLevel := utils.GetIntValueFiled(typemap, "alarmLevel")
			if configAlarmLevel > 0 && configAlarmLevel != alarmLevel {
				continue
			}
		}
		ExecuteNotifyConfig(db, notifyConfig, notifyData)
	}
}
